package action;

import controller.Action;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Curso;
import model.Professor;

public abstract class ManterCursoAction extends Action {

    @Override
    public void prepararOperacao(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            String action = request.getParameter("action");
            request.setAttribute("action", action);
            request.setAttribute("professores", Professor.obterProfessores());
            setParametros(request, response);
            RequestDispatcher view = request.getRequestDispatcher("/manterCurso.jsp");
            view.forward(request, response);
        } catch (ServletException e) {
            throw e;
        } catch (IOException e) {
            throw new ServletException(e);
        } catch (SQLException e) {
            throw new ServletException(e);
        } catch (ClassNotFoundException e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void confirmarOperacao(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            int codCurso = Integer.parseInt(request.getParameter("codCurso"));
            String nome = request.getParameter("nomeCurso");
            int cargaHoraria = Integer.parseInt(request.getParameter("cargaHoraria"));
            String tipoCurso = request.getParameter("tipoCurso");
            int totalPeriodos = Integer.parseInt(request.getParameter("totalPeriodos"));
            int matriculaProfessor = Integer.parseInt(request.getParameter("professorCoordenador"));
            Professor professor;
            if (matriculaProfessor != 0) {
                professor = Professor.obterProfessor(matriculaProfessor);
            } else {
                professor = null;
            }
            Curso curso = new Curso(codCurso, nome, cargaHoraria, tipoCurso, totalPeriodos, professor);
            efetuaPersistencia(curso);
            RequestDispatcher view = request.getRequestDispatcher("FrontController?action=PesquisarCurso");
            view.forward(request, response);
        } catch (ServletException e) {
            throw e;
        } catch (IOException e) {
            throw new ServletException(e);
        } catch (SQLException e) {
            throw new ServletException(e);
        } catch (ClassNotFoundException e) {
            throw new ServletException(e);
        }
    }

    public abstract void setParametros(HttpServletRequest request, HttpServletResponse response) throws ServletException;
    public abstract void efetuaPersistencia(Curso curso) throws ServletException;

}
